package com.cbs.android.function.imagepick;

import android.annotation.TargetApi;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.cbs.android.component.application.activity.CBSActivity;
import com.cbs.android.component.toast.Toast;
import com.cbs.android.function.imagepick.entity.ImageEntity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by broche on 8/22/16.
 */
public class ImagePickActivity extends CBSActivity {
    private static final String TAG = ImagePickActivity.class.getName();

    private MyAdapter myAdapter;
    private ImageView noImageView;

    private int selectCount = 1;
    private int curSelectedIndex = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.cbs_imagepick_activity_gallery);

        selectCount = getIntent().getIntExtra(ImagePickFunction.Extras.Count, 1);

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.cbs_imagepick_recyclerview);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(gridLayoutManager);
        myAdapter = new MyAdapter();
        recyclerView.setAdapter(myAdapter);

        if (selectCount > 1) {
            findViewById(R.id.cbs_imagepick_bottomcontainer).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.cbs_imagepick_bottomcontainer).setVisibility(View.GONE);
        }

        noImageView = (ImageView) findViewById(R.id.cbs_imagepick_noimage);

        findViewById(R.id.cbs_imagepick_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<ImageEntity> selected = new ArrayList<>(myAdapter.getSelected());

                List<String> result = new ArrayList<>();
                while (selected.size() > 0) {
                    ImageEntity tEntity = null;
                    for (int i = 0; i < selected.size(); i++) {
                        if (tEntity == null) {
                            tEntity = selected.get(i);
                        } else {
                            if (selected.get(i).getIndex() < tEntity.getIndex()) {
                                tEntity = selected.get(i);
                            } else {
                                // do nothing
                            }
                        }
                    }
                    if (tEntity != null) {
                        result.add(tEntity.getPath());
                        selected.remove(tEntity);
                    }
                }

                Intent data = new Intent().putExtra(ImagePickFunction.Extras.Result, result.toArray(new String[]{}));
                setResult(RESULT_OK, data);
                finish();
            }
        });

        loadData();
    }

    private void loadData() {
        myAdapter.addAll(getGalleryPhotos(MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
        myAdapter.addAll(getGalleryPhotos(MediaStore.Images.Media.INTERNAL_CONTENT_URI));
        myAdapter.notifyDataSetChanged();
        checkImageStatus();
    }

    private void checkImageStatus() {
        if (myAdapter.isEmpty()) {
            noImageView.setVisibility(View.VISIBLE);
        } else {
            noImageView.setVisibility(View.GONE);
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private ArrayList<ImageEntity> getGalleryPhotos(Uri uri) {
        ArrayList<ImageEntity> galleryList = new ArrayList<>();
        try {
            final String[] columns = {MediaStore.Images.Media.DATA,
                    MediaStore.Images.Media._ID};
            final String orderBy = MediaStore.Images.Media._ID;

            CursorLoader cursorLoader = new CursorLoader(this, uri, columns, null, null, orderBy);
            Cursor imagecursor = cursorLoader.loadInBackground();

            if (imagecursor != null && imagecursor.getCount() > 0) {

                while (imagecursor.moveToNext()) {
                    ImageEntity item = new ImageEntity();

                    int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);

                    item.setPath(imagecursor.getString(dataColumnIndex));

                    galleryList.add(item);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // show newest photo at beginning of the list
        Collections.reverse(galleryList);
        return galleryList;
    }

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
        private ArrayList<ImageEntity> data = new ArrayList<>();

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = getLayoutInflater().inflate(R.layout.cbs_imagepick_gallery_item, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            Glide.with(ImagePickActivity.this).load("file://" + data.get(position).getPath()).into(holder.imageView);
            if (selectCount > 1) {
                holder.checkView.setSelected(data.get(position).isSeleted());
            }

            holder.itemView.setTag(R.id.cbs_imagepick_tag1, position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        public boolean isMultiCountMeet() {
            int count = 0;
            for (ImageEntity aData : data) {
                if (aData.isSeleted()) {
                    count++;
                }
            }
            return count >= selectCount;
        }

        public ArrayList<ImageEntity> getSelected() {
            ArrayList<ImageEntity> dataT = new ArrayList<>();

            for (ImageEntity aData : data) {
                if (aData.isSeleted()) {
                    dataT.add(aData);
                }
            }

            return dataT;
        }

        public void addAll(ArrayList<ImageEntity> files) {
            this.data.addAll(files);
            notifyDataSetChanged();
        }

        public boolean isEmpty() {
            return data.size() == 0;
        }

        public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            ImageView imageView;
            ImageView checkView;

            public MyViewHolder(View itemView) {
                super(itemView);

                imageView = (ImageView) itemView.findViewById(R.id.cbs_imagepick_image);
                checkView = (ImageView) itemView.findViewById(R.id.cbs_imagepick_check);
                if (selectCount > 1) {
                    checkView.setVisibility(View.VISIBLE);
                } else {
                    checkView.setVisibility(View.GONE);
                }
                itemView.setOnClickListener(this);
            }

            @Override
            public void onClick(View v) {
                int position = (int) v.getTag(R.id.cbs_imagepick_tag1);
                if (selectCount > 1) {
                    if (data.get(position).isSeleted()) {
                        data.get(position).setSeleted(false);
                    } else {
                        if (!isMultiCountMeet()) {
                            data.get(position).setSeleted(true);
                            data.get(position).setIndex(curSelectedIndex++);
                        } else {
                            Toast.show(getResources().getString(R.string.cbs_imagepick_exceeded_popup));
                        }
                    }
                    checkView.setSelected(data.get(position).isSeleted());
                } else {
                    ImageEntity item = data.get(position);
                    Intent data = new Intent().putExtra(ImagePickFunction.Extras.Result, new String[]{item.getPath()});
                    setResult(RESULT_OK, data);
                    finish();
                }
            }
        }
    }
}
